﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Management;
using System.Threading;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;
using System.Runtime.InteropServices;
using System.Windows.Forms.DataVisualization.Charting;


namespace SteamMonitor
{
    public partial class SteamMonitor : Form
    {
// 数据定义
        private bool portstatus = false;

        private bool isRxShow = true;

        private bool isShowOriginData = false;

        //SerialPort serialPort = new SerialPort();
        // private string[] sSubKeys;
        private List<byte> receiveBuffer = new List<byte>();
        private int receiveCount = 0;
        private List<byte> sendBuffer = new List<byte>();
        private Queue<byte> bufferQueue = null;

        private bool isHeadReceived = false;

        //用于存放串口名和串口号
        private Dictionary<string, string> coms = new Dictionary<string, string>();
        private SortedDictionary<int, string> mycoms = new SortedDictionary<int, string>();

        private Queue<double>[] dataQueue = new Queue<double>[15]; //收到串口数据，如果是示波器数据则存入队列


//----------------------
        public SteamMonitor()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }


        /// <summary>
        /// 初始化窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            //设置串口号
            serialLoad();
            //实例化
            bufferQueue = new Queue<byte>();
            this.chart1.ChartAreas[0].AxisY.IsStartedFromZero = false;
        }

        private void getPortname()
        {
            mycoms.Clear();
            //获取计算机上的所有串口
            using (ManagementObjectSearcher searcher =
                   new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Name like '%(COM%'"))
            {
                var hardInfos = searcher.Get();
                foreach (var hardInfo in hardInfos)
                {
                    // Console.WriteLine(hardInfo.Properties["Name"].Value.ToString());
                    if (hardInfo.Properties["Name"].Value != null)
                    {
                        string deviceName = hardInfo.Properties["Name"].Value.ToString();
                        int startIndex = deviceName.IndexOf("(");
                        int endIndex = deviceName.IndexOf(")");
                        int temp = deviceName.IndexOf("-");
                        // Console.WriteLine(startIndex.ToString()+" "+endIndex+" "+temp);
                        // string key = deviceName.Substring(startIndex + 1, deviceName.Length - startIndex - 2);
                        string key;
                        if (temp != -1 && temp > startIndex)
                        {
                            key = deviceName.Substring(startIndex + 4, temp - startIndex - 4);
                        }
                        else
                        {
                            // Console.WriteLine(deviceName.Length);
                            key = deviceName.Substring(startIndex + 4, endIndex - startIndex - 4);
                        }

                        string name = deviceName.Substring(0, startIndex - 1);
                        Console.WriteLine("key:" + key + ",name:" + name + ",deviceName:" + deviceName);
                        // coms.Add(key,name);
                        if (mycoms.ContainsKey(Convert.ToInt32(key)) == false)
                            mycoms.Add(Convert.ToInt32(key), name);
                    }
                }
            }

            this.com_cbb.Items.Clear();
            //输出当前计算机的串口

            foreach (var item in mycoms)
            {
                // Console.WriteLine(aValue);
                string sValue = "COM" + item.Key.ToString();
                this.com_cbb.Items.Add(sValue);
            }
        }

        private const int WM_DEVICE_CHANGE = 0x219;
        private const int DBT_DEVICEARRIVAL = 0x8000;
        private const int DBT_DEVICE_REMOVE_COMPLETE = 0x8004;

        /// <summary>
        /// 检测USB串口的拔插
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICE_CHANGE) // 捕获USB设备的拔出消息WM_DEVICECHANGE
            {
                switch (m.WParam.ToInt32())
                {
                    case DBT_DEVICE_REMOVE_COMPLETE: // USB拔出
                    {
                        new Thread(
                            new ThreadStart(
                                new Action(() =>
                                {
                                    mycoms.Clear();
                                    getPortname();
                                })
                            )
                        ).Start();
                    }
                        break;
                    case DBT_DEVICEARRIVAL: // USB插入获取对应串口名称
                    {
                        new Thread(
                            new ThreadStart(
                                new Action(() =>
                                {
                                    mycoms.Clear();
                                    getPortname();
                                })
                            )
                        ).Start();
                    }
                        break;
                }
            }

            base.WndProc(ref m);
        }

        private void serialLoad()
        {
            getPortname();
            this.ysize_nud.Value = 0;
            this.xsize_nud.Value = 40;
            for (int i = 0; i < 15; i++)
                if (dataQueue[i] == null)
                    dataQueue[i] = new Queue<double>();

            //读取窗体上次的设置
            this.com_cbb.SelectedIndex = Properties.Settings.Default.com_cbb;
            this.baud_cbb.SelectedIndex = Properties.Settings.Default.baud_cbb;
            this.databit_cbb.SelectedIndex = Properties.Settings.Default.databit_cbb;
            this.check_cbb.SelectedIndex = Properties.Settings.Default.check_cbb;
            this.stopbit_cbb.SelectedIndex = Properties.Settings.Default.stopbit_cbb;
            this.coding_cbb.SelectedIndex = Properties.Settings.Default.coding_cbb;
            this.append_cbb.SelectedIndex = Properties.Settings.Default.append_cbb;
            this.send_tb.Text = Properties.Settings.Default.send_tb;
            this.textBox1.Text = Properties.Settings.Default.textBox1;
            this.textBox2.Text = Properties.Settings.Default.textBox2;
            this.textBox3.Text = Properties.Settings.Default.textBox3;
            this.textBox4.Text = Properties.Settings.Default.textBox4;
            this.textBox5.Text = Properties.Settings.Default.textBox5;
            this.textBox6.Text = Properties.Settings.Default.textBox6;
            this.textBox7.Text = Properties.Settings.Default.textBox7;
            this.textBox8.Text = Properties.Settings.Default.textBox8;
            this.textBox9.Text = Properties.Settings.Default.textBox9;
            this.textBox10.Text = Properties.Settings.Default.textBox10;
            this.textBox11.Text = Properties.Settings.Default.textBox11;
            this.textBox12.Text = Properties.Settings.Default.textBox12;
            this.textBox13.Text = Properties.Settings.Default.textBox13;
            this.textBox14.Text = Properties.Settings.Default.textBox14;
            this.textBox15.Text = Properties.Settings.Default.textBox15;
            this.textBox16.Text = Properties.Settings.Default.textBox16;
            this.data1_chb.Checked = Properties.Settings.Default.data1_chb;
            this.data2_chb.Checked = Properties.Settings.Default.data2_chb;
            this.data3_chb.Checked = Properties.Settings.Default.data3_chb;
            this.data4_chb.Checked = Properties.Settings.Default.data4_chb;
            this.data5_chb.Checked = Properties.Settings.Default.data5_chb;
            this.data6_chb.Checked = Properties.Settings.Default.data6_chb;
            this.data7_chb.Checked = Properties.Settings.Default.data7_chb;
            this.data8_chb.Checked = Properties.Settings.Default.data8_chb;
            this.data9_chb.Checked = Properties.Settings.Default.data9_chb;
            this.data10_chb.Checked = Properties.Settings.Default.data10_chb;
            this.data11_chb.Checked = Properties.Settings.Default.data11_chb;
            this.data12_chb.Checked = Properties.Settings.Default.data12_chb;
            this.data13_chb.Checked = Properties.Settings.Default.data13_chb;
            this.data14_chb.Checked = Properties.Settings.Default.data14_chb;
            this.data15_chb.Checked = Properties.Settings.Default.data15_chb;
            this.allselect_chb.Checked = Properties.Settings.Default.selectall_chb;
            this.reset_chb.Checked = Properties.Settings.Default.reset_chb;
            this.showchartdata_chb.Checked = Properties.Settings.Default.showchartdata_chb;

            timer1.Start();
        }


        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen == false)
            {
                serialPort1.PortName = this.com_cbb.Text;
                serialPort1.BaudRate = Convert.ToInt32(this.baud_cbb.Text);
                serialPort1.DataBits = Convert.ToInt32(this.databit_cbb.Text);
                switch (this.check_cbb.SelectedIndex)
                {
                    case 0:
                        serialPort1.Parity = Parity.None;
                        break;
                    case 1:
                        serialPort1.Parity = Parity.Odd;
                        break;
                    case 2:
                        serialPort1.Parity = Parity.Even;
                        break;
                    default:
                        serialPort1.Parity = Parity.None;
                        break;
                }

                switch (stopbit_cbb.SelectedIndex)
                {
                    case 0:
                        serialPort1.StopBits = StopBits.One;
                        break;
                    case 1:
                        serialPort1.StopBits = StopBits.OnePointFive;
                        break;
                    case 2:
                        serialPort1.StopBits = StopBits.Two;
                        break;
                    default:
                        serialPort1.StopBits = StopBits.One;
                        break;
                }
            }

            try
            {
                serialPort1.Open(); //打开串口
                portstatus = true;
                this.openbtn.BackColor = Color.DodgerBlue;
            }
            catch (Exception ex)
            {
                if (portstatus == true)
                {
                    MessageBox.Show("串口已经打开");
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            if (portstatus == true)
            {
                try
                {
                    serialPort1.Close();
                    portstatus = false;
                    this.openbtn.BackColor = Color.White;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("串口未开启");
            }
        }

        private void com_cbb_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.comtype.Text = mycoms[Convert.ToInt32(com_cbb.Text.Substring(3))];
            // Console.WriteLine(mycoms[Convert.ToInt32(com_cbb.Text.Substring(3))]);
        }

        private void sendbtn_Click(object sender, EventArgs e)
        {
            // Console.WriteLine(sender.ToString());
            if (this.send_tb.Text != "" && serialPort1.IsOpen)
            {
                string s = this.send_tb.Text;
                string a = this.append_cbb.Text;
                a = a.Replace("\\n", "\n");
                a = a.Replace("\\r", "\r");
                // Console.WriteLine(a);
                if (a != "None")
                    s += a;
                Console.WriteLine(s);
                serialPort1.Write(s);
                DateTime now = DateTime.Now;
                // now = now.AddHours(8);
                receive_tb.SelectionColor = Color.FromArgb(43, 132, 255);
                this.receive_tb.AppendText("\r\n" + now.ToString("[HH:mm:ss:fff] "));
                receive_tb.SelectionColor = Color.FromArgb(102, 168, 31);
                this.receive_tb.AppendText(s);
                this.receive_tb.ScrollToCaret();
            }
            else
            {
                if (serialPort1.IsOpen == false)
                    MessageBox.Show("请先打开串口");
                else if (this.send_tb.Text == "")
                    MessageBox.Show("发送数据不能为空");
            }
        }

        private string scopeBuffer = "";
        private int endUnfind = 0;
        private bool isScopedata = false;

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string receiveStr = serialPort1.ReadExisting();
            if (isRxShow == false)
            {
                receiveStr = "";
                return;
            }

            // byte[] dataTemp = new byte[serialPort1.BytesToRead];
            // serialPort1.Read(dataTemp, 0, dataTemp.Length);
            // receiveBuffer.AddRange(dataTemp);
            // receiveCount += dataTemp.Length;
            this.BeginInvoke(new EventHandler(delegate
            {
                string str = receiveStr;
                //将receivStr转换成指定编码

                // switch (coding_cbb.SelectedIndex)
                // {
                //     case 0:
                //         str = Encoding.GetEncoding("GBK").GetString(Encoding.Default.GetBytes(receiveStr));
                //         break;
                //     case 1:
                //         str = Encoding.GetEncoding("UTF-8").GetString(Encoding.Default.GetBytes(receiveStr));
                //         break;
                //     default:
                //         str = Encoding.GetEncoding("GBK").GetString(Encoding.Default.GetBytes(receiveStr));
                //         break;
                //         
                //     // case 0:
                //     //     str=Encoding.GetEncoding("GBK").GetString(receiveBuffer.ToArray());
                //     //     break;
                //     // case 1:
                //     //     str=Encoding.GetEncoding("UTF-8").GetString(receiveBuffer.ToArray());
                //     //     break;
                //     // default:
                //     //     str=Encoding.GetEncoding("GBK").GetString(receiveBuffer.ToArray());
                //     //     break;
                // }
                //判断接收到的数据中有没有示波器数据

                // Console.WriteLine(DateTime.Now+str+" "+beginindex+" "+endindex);
                // if (beginindex != -1 && endindex != -1 && beginindex < endindex)
                // {
                //     // Console.WriteLine(beginindex+" "+endindex);
                //     string data = str.Substring(beginindex + 4, endindex - beginindex-4);
                //     // Console.WriteLine(data);
                //     string[] dataArr = data.Split(',');
                //     int sIndex = 0;
                //     foreach (string s in dataArr)
                //     {
                //         // Console.WriteLine(s);
                //         if (sIndex < 15)
                //         {
                //             if (dataQueue[sIndex] == null)
                //             {
                //                 dataQueue[sIndex] = new Queue<double>();
                //             }
                //             string[] channel = s.Split(' ');
                //             chart1.Series[sIndex].Name=channel[0];
                //             dataQueue[sIndex].Enqueue(Convert.ToDouble(channel[1]));
                //         }
                //         sIndex++;
                //     }
                // }


                //把str按照\r\n分割成多个字符串显示在接收框中
                string[] strArray = str.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string s in strArray)
                {
                    // Console.WriteLine("datas:"+s);
                    int beginindex = s.IndexOf("$");
                    int endindex;
                    if (beginindex != -1 || isHeadReceived)
                    {
                        if (isHeadReceived && beginindex != -1)
                        {
                            //丢弃还未接受完的帧
                            scopeBuffer = "";
                            isHeadReceived = false;
                        }

                        isHeadReceived = true;
                        scopeBuffer += s;
                        endindex = scopeBuffer.IndexOf("@"); //ch1:test 25,befor 26end
                        // Console.WriteLine(isHeadReceived+" "+endindex+" "+endUnfind);
                        if (endindex != -1)
                        {
                            beginindex = scopeBuffer.IndexOf("ch1:");
                            // Console.WriteLine("scop:"+scopeBuffer);
                            string data = scopeBuffer.Substring(beginindex + 2, endindex - beginindex - 2);
                            // Console.WriteLine(scopeBuffer+" "+ data);
                            string[] dataArr = data.Split(',');
                            int sIndex = 0;
                            foreach (string subs in dataArr)
                            {
                                // Console.WriteLine(s);
                                if (sIndex < 15)
                                {
                                    if (dataQueue[sIndex] == null)
                                    {
                                        dataQueue[sIndex] = new Queue<double>();
                                    }

                                    string[] channel = subs.Split(' ');
                                    // Console.WriteLine("data:"+data+"       "+subs+"      oristring "+s);
                                    chart1.Series[sIndex].Name = channel[0];
                                    switch (sIndex)
                                    {
                                        case 0:
                                            data1_chb.Text = channel[0];
                                            break;
                                        case 1:
                                            data2_chb.Text = channel[0];
                                            break;
                                        case 2:
                                            data3_chb.Text = channel[0];
                                            break;
                                        case 3:
                                            data4_chb.Text = channel[0];
                                            break;
                                        case 4:
                                            data5_chb.Text = channel[0];
                                            break;
                                        case 5:
                                            data6_chb.Text = channel[0];
                                            break;
                                        case 6:
                                            data7_chb.Text = channel[0];
                                            break;
                                        case 7:
                                            data8_chb.Text = channel[0];
                                            break;
                                        case 8:
                                            data9_chb.Text = channel[0];
                                            break;
                                        case 9:
                                            data10_chb.Text = channel[0];
                                            break;
                                        case 10:
                                            data11_chb.Text = channel[0];
                                            break;
                                        case 11:
                                            data12_chb.Text = channel[0];
                                            break;
                                        case 12:
                                            data13_chb.Text = channel[0];
                                            break;
                                        case 13:
                                            data14_chb.Text = channel[0];
                                            break;
                                        case 14:
                                            data15_chb.Text = channel[0];
                                            break;
                                        default:
                                            break;
                                    }

                                    dataQueue[sIndex].Enqueue(Convert.ToDouble(channel[1]));
                                    isScopedata = true;
                                }

                                sIndex++;
                            }

                            isHeadReceived = false;
                            scopeBuffer = "";
                            endUnfind = 0;
                        }
                        else
                        {
                            endUnfind++;
                            if (endUnfind > 4)
                            {
                                isHeadReceived = false;
                                scopeBuffer = "";
                                endUnfind = 0;
                            }
                        }
                    }

                    // Console.WriteLine(s+" "+isHeadReceived+" "+isScopedata+" "+endUnfind);
                    // Console.WriteLine();
                    if ((isHeadReceived == false && isScopedata == false) || isShowOriginData == true)
                    {
                        //如果s是换行直接跳过
                        if (s.Equals("\n") || s.Equals("\r") || s.Equals("\r\n"))
                            break;
                        DateTime now = DateTime.Now;
                        // now = now.AddHours(8);
                        receive_tb.SelectionColor = Color.FromArgb(43, 132, 255);
                        this.receive_tb.AppendText("\r\n" + now.ToString("[HH:mm:ss:fff] "));
                        receive_tb.SelectionColor = Color.FromArgb(1, 2, 255);
                        this.receive_tb.AppendText(s);
                        // Console.WriteLine(s);
                        this.receive_tb.ScrollToCaret();
                    }
                    else if (isScopedata == true)
                    {
                        isScopedata = false;
                    }
                }

                receiveBuffer.Clear();
            }));
        }

        private void pause_btn_Click(object sender, EventArgs e)
        {
            if (isRxShow == true)
            {
                isRxShow = false;
                this.pause_btn.Text = "继续";
            }
            else
            {
                isRxShow = true;
                this.pause_btn.Text = "暂停";
            }
        }

        private void clearbtn_Click(object sender, EventArgs e)
        {
            this.BeginInvoke(new EventHandler(delegate
            {
                receiveBuffer.Clear();
                receiveCount = 0;
                this.receive_tb.Text = "";
                for (int i = 0; i < 15; i++)
                {
                    chart1.Series[i].Points.Clear();
                    chart1.Series[i].Name = "Data" + (i + 1).ToString();
                    switch (i)
                    {
                        case 0:
                            data1_chb.Text = "Data1";
                            data1_lb.Text = "0";
                            break;
                        case 1:
                            data2_chb.Text = "Data2";
                            data2_lb.Text = "0";
                            break;
                        case 2:
                            data3_chb.Text = "Data3";
                            data3_lb.Text = "0";
                            break;
                        case 3:
                            data4_chb.Text = "Data4";
                            data4_lb.Text = "0";
                            break;
                        case 4:
                            data5_chb.Text = "Data5";
                            data5_lb.Text = "0";
                            break;
                        case 5:
                            data6_chb.Text = "Data6";
                            data6_lb.Text = "0";
                            break;
                        case 6:
                            data7_chb.Text = "Data7";
                            data7_lb.Text = "0";
                            break;
                        case 7:
                            data8_chb.Text = "Data8";
                            data8_lb.Text = "0";
                            break;
                        case 8:
                            data9_chb.Text = "Data9";
                            data9_lb.Text = "0";
                            break;
                        case 9:
                            data10_chb.Text = "Data10";
                            data10_lb.Text = "0";
                            break;
                        case 10:
                            data11_chb.Text = "Data11";
                            data11_lb.Text = "0";
                            break;
                        case 11:
                            data12_chb.Text = "Data12";
                            data12_lb.Text = "0";
                            break;
                        case 12:
                            data13_chb.Text = "Data13";
                            data13_lb.Text = "0";
                            break;
                        case 13:
                            data14_chb.Text = "Data14";
                            data14_lb.Text = "0";
                            break;
                        case 14:
                            data15_chb.Text = "Data15";
                            data15_lb.Text = "0";
                            break;
                        default:
                            break;
                    }
                }
                //设置chart的x轴位置为0
                chart1.ChartAreas[0].AxisX.ScaleView.Position = 0;
            }));
        }


        private void cmdsend_btn_click(object sender, EventArgs e)
        {
            string str = sender.ToString();
            //提取按钮编号，编号位于Text: 之后
            int index = str.IndexOf("Text: ") + 6;
            str = str.Substring(index);
            int cmdNum = Convert.ToInt32(str);
            switch (cmdNum)
            {
                case 1:
                    cmdSend(this.textBox1.Text);
                    break;
                case 2:
                    cmdSend(textBox2.Text);
                    break;
                case 3:
                    cmdSend(textBox3.Text);
                    break;
                case 4:
                    cmdSend(textBox4.Text);
                    break;
                case 5:
                    cmdSend(textBox5.Text);
                    break;
                case 6:
                    cmdSend(textBox6.Text);
                    break;
                case 7:
                    cmdSend(textBox7.Text);
                    break;
                case 8:
                    cmdSend(textBox8.Text);
                    break;
                case 9:
                    cmdSend(textBox9.Text);
                    break;
                case 10:
                    cmdSend(textBox10.Text);
                    break;
                case 11:
                    cmdSend(textBox11.Text);
                    break;
                case 12:
                    cmdSend(textBox12.Text);
                    break;
                case 13:
                    cmdSend(textBox13.Text);
                    break;
                case 14:
                    cmdSend(textBox14.Text);
                    break;
                case 15:
                    cmdSend(textBox15.Text);
                    break;
                case 16:
                    cmdSend(textBox16.Text);
                    break;
                default:
                    break;
            }
        }

        private void cmdSend(string sendStr)
        {
            // Console.WriteLine(sender.ToString());
            if (sendStr != "" && serialPort1.IsOpen)
            {
                // string s= this.send_tb.Text;
                switch (append_cbb.SelectedIndex)
                {
                    case 0:
                        break;
                    case 1:
                        sendStr += "\n";
                        break;
                    case 2:
                        sendStr += "\r";
                        break;
                    case 3:
                        sendStr += "\n\r";
                        break;
                    case 4:
                        sendStr += "\r\n";
                        break;
                    default:
                        break;
                }

                Console.WriteLine(sendStr);
                serialPort1.Write(sendStr);
                DateTime now = DateTime.Now;
                // now = now.AddHours(8);
                receive_tb.SelectionColor = Color.FromArgb(43, 132, 255);
                this.receive_tb.AppendText("\r\n" + now.ToString("[HH:mm:ss:fff] "));
                receive_tb.SelectionColor = Color.FromArgb(102, 168, 31);
                this.receive_tb.AppendText(sendStr);
                this.receive_tb.ScrollToCaret();
            }
            else
            {
                if (serialPort1.IsOpen == false)
                    MessageBox.Show("请先打开串口");
                else if (this.send_tb.Text == "")
                    MessageBox.Show("发送数据不能为空");
            }
        }

        private void SteamMonitor_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }

            Properties.Settings.Default.com_cbb = this.com_cbb.SelectedIndex;
            Properties.Settings.Default.baud_cbb = this.baud_cbb.SelectedIndex;
            Properties.Settings.Default.databit_cbb = this.databit_cbb.SelectedIndex;
            Properties.Settings.Default.check_cbb = this.check_cbb.SelectedIndex;
            Properties.Settings.Default.stopbit_cbb = this.stopbit_cbb.SelectedIndex;
            Properties.Settings.Default.append_cbb = this.append_cbb.SelectedIndex;
            Properties.Settings.Default.coding_cbb = this.coding_cbb.SelectedIndex;
            Properties.Settings.Default.send_tb = this.send_tb.Text;
            Properties.Settings.Default.textBox1 = this.textBox1.Text;
            Properties.Settings.Default.textBox2 = this.textBox2.Text;
            Properties.Settings.Default.textBox3 = this.textBox3.Text;
            Properties.Settings.Default.textBox4 = this.textBox4.Text;
            Properties.Settings.Default.textBox5 = this.textBox5.Text;
            Properties.Settings.Default.textBox6 = this.textBox6.Text;
            Properties.Settings.Default.textBox7 = this.textBox7.Text;
            Properties.Settings.Default.textBox8 = this.textBox8.Text;
            Properties.Settings.Default.textBox9 = this.textBox9.Text;
            Properties.Settings.Default.textBox10 = this.textBox10.Text;
            Properties.Settings.Default.textBox11 = this.textBox11.Text;
            Properties.Settings.Default.textBox12 = this.textBox12.Text;
            Properties.Settings.Default.textBox13 = this.textBox13.Text;
            Properties.Settings.Default.textBox14 = this.textBox14.Text;
            Properties.Settings.Default.textBox15 = this.textBox15.Text;
            Properties.Settings.Default.textBox16 = this.textBox16.Text;
            Properties.Settings.Default.data1_chb = this.data1_chb.Checked;
            Properties.Settings.Default.data2_chb = this.data2_chb.Checked;
            Properties.Settings.Default.data3_chb = this.data3_chb.Checked;
            Properties.Settings.Default.data4_chb = this.data4_chb.Checked;
            Properties.Settings.Default.data5_chb = this.data5_chb.Checked;
            Properties.Settings.Default.data6_chb = this.data6_chb.Checked;
            Properties.Settings.Default.data7_chb = this.data7_chb.Checked;
            Properties.Settings.Default.data8_chb = this.data8_chb.Checked;
            Properties.Settings.Default.data9_chb = this.data9_chb.Checked;
            Properties.Settings.Default.data10_chb = this.data10_chb.Checked;
            Properties.Settings.Default.data11_chb = this.data11_chb.Checked;
            Properties.Settings.Default.data12_chb = this.data12_chb.Checked;
            Properties.Settings.Default.data13_chb = this.data13_chb.Checked;
            Properties.Settings.Default.data14_chb = this.data14_chb.Checked;
            Properties.Settings.Default.data15_chb = this.data15_chb.Checked;
            Properties.Settings.Default.selectall_chb = this.allselect_chb.Checked;
            Properties.Settings.Default.reset_chb = this.reset_chb.Checked;
            Properties.Settings.Default.showchartdata_chb = this.showchartdata_chb.Checked;
            Properties.Settings.Default.Save();
        }

        //触发按钮，点击开始在chart显示随机数
        private void charttest_btn_Click(object sender, EventArgs e)
        {
            if (timer1.Enabled == false)
            {
                timer1.Start();
                this.charttest_btn.Text = "停止";
            }
            else
            {
                timer1.Stop();
                this.charttest_btn.Text = "开始";
            }
        }

        //注册timer事件
        Random random = new Random();

        private Data data = new Data(Double.MinValue, Double.MaxValue);

        // int x = 0;
        int y = 0;
        private Boolean isAotoSize = true;

        private void timer1_Tick(object sender, EventArgs e)
        {
            // y=random.Next(0,35);
            // Console.WriteLine(dataQueue[0].Count);
            if (dataQueue[0].Count > 0)
            {
                this.chart1.Series[0].Points.AddY(dataQueue[0].Peek());
                data.Max = dataQueue[0].Peek() > data.Max ? dataQueue[0].Peek() : data.Max;
                data.Min = dataQueue[0].Peek() < data.Min ? dataQueue[0].Peek() : data.Min;
                data1_lb.Text = dataQueue[0].Dequeue().ToString();
            }

            // y = random.Next(0, 35);
            if (dataQueue[1].Count > 0)
            {
                this.chart1.Series[1].Points.AddY(dataQueue[1].Peek());
                data.Max = dataQueue[1].Peek() > data.Max ? dataQueue[1].Peek() : data.Max;
                data.Min = dataQueue[1].Peek() < data.Min ? dataQueue[1].Peek() : data.Min;
                data2_lb.Text = dataQueue[1].Dequeue().ToString();
            }

            // y=random.Next(0,35);
            if (dataQueue[2].Count > 0)
            {
                this.chart1.Series[2].Points.AddY(dataQueue[2].Peek());
                data.Max = dataQueue[2].Peek() > data.Max ? dataQueue[2].Peek() : data.Max;
                data.Min = dataQueue[2].Peek() < data.Min ? dataQueue[2].Peek() : data.Min;
                data3_lb.Text = dataQueue[2].Dequeue().ToString();
            }

            // y=random.Next(0,35);
            if (dataQueue[3].Count > 0)
            {
                this.chart1.Series[3].Points.AddY(dataQueue[3].Peek());
                data.Max = dataQueue[3].Peek() > data.Max ? dataQueue[3].Peek() : data.Max;
                data.Min = dataQueue[3].Peek() < data.Min ? dataQueue[3].Peek() : data.Min;
                data4_lb.Text = dataQueue[3].Dequeue().ToString();
            }

            // y=random.Next(0,35);
            if (dataQueue[4].Count > 0)
            {
                this.chart1.Series[4].Points.AddY(dataQueue[4].Peek());
                data.Max = dataQueue[4].Peek() > data.Max ? dataQueue[4].Peek() : data.Max;
                data.Min = dataQueue[4].Peek() < data.Min ? dataQueue[4].Peek() : data.Min;
                data5_lb.Text = dataQueue[4].Dequeue().ToString();
            }

            if (dataQueue[5].Count > 0)
            {
                this.chart1.Series[5].Points.AddY(dataQueue[5].Peek());
                data.Max = dataQueue[5].Peek() > data.Max ? dataQueue[5].Peek() : data.Max;
                data.Min = dataQueue[5].Peek() < data.Min ? dataQueue[5].Peek() : data.Min;
                data6_lb.Text = dataQueue[5].Dequeue().ToString();
            }

            if (dataQueue[6].Count > 0)
            {
                this.chart1.Series[6].Points.AddY(dataQueue[6].Peek());
                data.Max = dataQueue[6].Peek() > data.Max ? dataQueue[6].Peek() : data.Max;
                data.Min = dataQueue[6].Peek() < data.Min ? dataQueue[6].Peek() : data.Min;
                data7_lb.Text = dataQueue[6].Dequeue().ToString();
            }

            if (dataQueue[7].Count > 0)
            {
                this.chart1.Series[7].Points.AddY(dataQueue[7].Peek());
                data.Max = dataQueue[7].Peek() > data.Max ? dataQueue[7].Peek() : data.Max;
                data.Min = dataQueue[7].Peek() < data.Min ? dataQueue[7].Peek() : data.Min;
                data8_lb.Text = dataQueue[7].Dequeue().ToString();
            }


            if (dataQueue[8].Count > 0)
            {
                this.chart1.Series[8].Points.AddY(dataQueue[8].Peek());
                data.Max = dataQueue[8].Peek() > data.Max ? dataQueue[8].Peek() : data.Max;
                data.Min = dataQueue[8].Peek() < data.Min ? dataQueue[8].Peek() : data.Min;
                data9_lb.Text = dataQueue[8].Dequeue().ToString();
            }

            if (dataQueue[9].Count > 0)
            {
                this.chart1.Series[9].Points.AddY(dataQueue[9].Peek());
                data.Max = dataQueue[9].Peek() > data.Max ? dataQueue[9].Peek() : data.Max;
                data.Min = dataQueue[9].Peek() < data.Min ? dataQueue[9].Peek() : data.Min;
                data10_lb.Text = dataQueue[9].Dequeue().ToString();
            }

            if (dataQueue[10].Count > 0)
            {
                this.chart1.Series[10].Points.AddY(dataQueue[10].Peek());
                data.Max = dataQueue[10].Peek() > data.Max ? dataQueue[10].Peek() : data.Max;
                data.Min = dataQueue[10].Peek() < data.Min ? dataQueue[10].Peek() : data.Min;
                data11_lb.Text = dataQueue[10].Dequeue().ToString();
            }

            if (dataQueue[11].Count > 0)
            {
                this.chart1.Series[11].Points.AddY(dataQueue[11].Peek());
                data.Max = dataQueue[11].Peek() > data.Max ? dataQueue[11].Peek() : data.Max;
                data.Min = dataQueue[11].Peek() < data.Min ? dataQueue[11].Peek() : data.Min;
                data12_lb.Text = dataQueue[11].Dequeue().ToString();
            }

            if (dataQueue[12].Count > 0)
            {
                this.chart1.Series[12].Points.AddY(dataQueue[12].Peek());
                data.Max = dataQueue[12].Peek() > data.Max ? dataQueue[12].Peek() : data.Max;
                data.Min = dataQueue[12].Peek() < data.Min ? dataQueue[12].Peek() : data.Min;
                data13_lb.Text = dataQueue[12].Dequeue().ToString();
            }

            if (dataQueue[13].Count > 0)
            {
                this.chart1.Series[13].Points.AddY(dataQueue[13].Peek());
                data.Max = dataQueue[13].Peek() > data.Max ? dataQueue[13].Peek() : data.Max;
                data.Min = dataQueue[13].Peek() < data.Min ? dataQueue[13].Peek() : data.Min;
                data14_lb.Text = dataQueue[13].Dequeue().ToString();
            }

            if (dataQueue[14].Count > 0)
            {
                this.chart1.Series[14].Points.AddY(dataQueue[14].Peek());
                data.Max = dataQueue[14].Peek() > data.Max ? dataQueue[14].Peek() : data.Max;
                data.Min = dataQueue[14].Peek() < data.Min ? dataQueue[14].Peek() : data.Min;
                data15_lb.Text = dataQueue[14].Dequeue().ToString();
            }


            if (isChartMoved == false && chart1.ChartAreas[0].AxisX.Maximum > 40) //转到最新数据
            {
                chart1.ChartAreas[0].AxisX.ScaleView.Scroll(chart1.ChartAreas[0].AxisX.Maximum);
            }

            // Console.WriteLine(data.Max==Double.MinValue);
            if (data.Max != Double.MinValue && isAotoSize)
            {
                this.ysize_nud.Value = (decimal)((data.Max - data.Min) * 1.2);
            }
        }

        private void chart1_MouseWheel(object sender, MouseEventArgs e)
        {
            if (Double.IsNaN(chart1.ChartAreas[0].AxisX.ScaleView.Size))
            {
                chart1.ChartAreas[0].AxisX.ScaleView.Size = 40;
                // Console.WriteLine(chart1.ChartAreas[0].AxisX.ScaleView.Size);
            }

            if (Double.IsNaN(chart1.ChartAreas[0].AxisY.ScaleView.Size))
            {
                chart1.ChartAreas[0].AxisY.ScaleView.Size = (data.Max - data.Min) * 1.2;
                // Console.WriteLine(chart1.ChartAreas[0].AxisY.ScaleView.Size);
            }

            chart1.ChartAreas[0].AxisX.ScaleView.Size = chart1.ChartAreas[0].AxisX.ScaleView.Size - (e.Delta / 120) < 1
                ? 1
                : chart1.ChartAreas[0].AxisX.ScaleView.Size - (e.Delta / 120);
            chart1.ChartAreas[0].AxisY.ScaleView.Size = chart1.ChartAreas[0].AxisY.ScaleView.Size - (e.Delta / 120) < 1
                ? 1
                : chart1.ChartAreas[0].AxisY.ScaleView.Size - (e.Delta / 120);
            xsize_nud.Value = (decimal)chart1.ChartAreas[0].AxisX.ScaleView.Size;
            ysize_nud.Value = (decimal)chart1.ChartAreas[0].AxisY.ScaleView.Size;
            isAotoSize = false;
        }

        private bool isMouseDown = false;
        private Point LastPoint;
        private bool isLeftButton = false;

        private bool isChartMoved = false;

        //记录鼠标按下时鼠标的像素位置
        private Point LastMove;
        private double LastXPosition = 0;
        private double LastYPosition = 0;
        private double LastXSize = 0;
        private double LastYSize = 0;

        private void chart1_MouseMove(object sender, MouseEventArgs e)
        {
            //输出鼠标移动了多少
            // Console.WriteLine(e.X);

            if (isMouseDown)
            {
                if (isLeftButton)
                {
                    chart1.ChartAreas[0].AxisX.ScaleView.Position = LastXPosition -
                                                                    ((double)(e.X - LastMove.X) / chart1.Size.Width) *
                                                                    chart1.ChartAreas[0].AxisX.ScaleView.Size;
                    chart1.ChartAreas[0].AxisX.ScaleView.Position = chart1.ChartAreas[0].AxisX.ScaleView.Position < 0
                        ? 0
                        : chart1.ChartAreas[0].AxisX.ScaleView.Position;
                    if (Double.IsNaN(chart1.ChartAreas[0].AxisY.ScaleView.Size))
                        chart1.ChartAreas[0].AxisY.ScaleView.Size = (data.Max - data.Min) * 1.2;
                    chart1.ChartAreas[0].AxisY.ScaleView.Position = LastYPosition +
                                                                    ((double)(e.Y - LastMove.Y) / chart1.Size.Height) *
                                                                    chart1.ChartAreas[0].AxisY.ScaleView.Size;
                    //把当前鼠标位置的图像移动到鼠标松开的地方


                    isChartMoved = true;
                }
                else
                {
                    Console.WriteLine((double)(e.Y - LastMove.Y) / chart1.Size.Height *
                                      chart1.ChartAreas[0].AxisY.ScaleView.Size);
                    chart1.ChartAreas[0].AxisY.ScaleView.Size = LastYSize +
                                                                ((double)(e.Y - LastMove.Y) / chart1.Size.Height) *
                                                                chart1.ChartAreas[0].AxisY.ScaleView.Size;
                    chart1.ChartAreas[0].AxisY.ScaleView.Size = chart1.ChartAreas[0].AxisY.ScaleView.Size < 0
                        ? 0
                        : chart1.ChartAreas[0].AxisY.ScaleView.Size;
                    chart1.ChartAreas[0].AxisX.ScaleView.Size = LastXSize -
                                                                ((double)(e.X - LastMove.X) / chart1.Size.Width) *
                                                                chart1.ChartAreas[0].AxisX.ScaleView.Size;
                    chart1.ChartAreas[0].AxisX.ScaleView.Size = chart1.ChartAreas[0].AxisX.ScaleView.Size < 0
                        ? 0
                        : chart1.ChartAreas[0].AxisX.ScaleView.Size;
                    xsize_nud.Value = (decimal)chart1.ChartAreas[0].AxisX.ScaleView.Size;
                    ysize_nud.Value = (decimal)chart1.ChartAreas[0].AxisY.ScaleView.Size;
                }

                LastPoint = new Point(e.X, e.Y);
                isAotoSize = false;
            }
            else
            {
                //获取离鼠标最近的点的x轴坐标,
                // int xValue = Convert.ToInt32(chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.X));
                //将cusor设置到这个位置
                chart1.ChartAreas[0].CursorX.SetCursorPixelPosition(new Point(e.X, e.Y), true);
                // Console.WriteLine(chart1.ChartAreas[0].CursorX.Position);
                //将cusor设置到这个位置
                // chart1.ChartAreas[0].CursorY.SetCursorPixelPosition(new Point(e.X, e.Y), true);
            }
        }

        private void chart1_MouseDown(object sender, MouseEventArgs e)
        {
            //输出鼠标按下了多少
            // Console.WriteLine(e.Button);
            isMouseDown = true;
            LastPoint = new Point(e.X, e.Y);
            LastMove = new Point(e.X, e.Y);
            LastXPosition = chart1.ChartAreas[0].AxisX.ScaleView.Position;
            LastYPosition = chart1.ChartAreas[0].AxisY.ScaleView.Position;
            isLeftButton = e.Button == MouseButtons.Left ? true : false;

            LastXSize = chart1.ChartAreas[0].AxisX.ScaleView.Size;
            LastYSize = chart1.ChartAreas[0].AxisY.ScaleView.Size;
            // Console.WriteLine(isLeftButton);
        }

        private void chart1_MouseUp(object sender, MouseEventArgs e)
        {
            //输出鼠标抬起了多少
            // Console.WriteLine(e.X);
            isMouseDown = false;
        }

        private void chart1_AxisScrollBarClicked(object sender, ScrollBarEventArgs e)
        {
            // Console.WriteLine(e.ChartArea);
            //输出滚动条当前为位置
            Console.WriteLine(e.Axis.ScaleView.Position);
        }

        private void chart1_DoubleClick(object sender, EventArgs e)
        {
            // chart1.ChartAreas[0].AxisX.ScaleView.Scroll(chart1.ChartAreas[0].AxisX.ScaleView.Position);
            isChartMoved = false;
            if (reset_chb.Checked)
            {
                chart1.ChartAreas[0].AxisY.ScaleView.Position = data.Min - (data.Max - data.Min) * 0.1;
                chart1.ChartAreas[0].AxisY.ScaleView.Size = (data.Max - data.Min) * 1.2;
                chart1.ChartAreas[0].AxisX.ScaleView.Size = 40;
                ysize_nud.Value = (decimal)chart1.ChartAreas[0].AxisY.ScaleView.Size;
                xsize_nud.Value = (decimal)chart1.ChartAreas[0].AxisX.ScaleView.Size;
                isAotoSize = true;
            }
        }

        private void chart1_GetToolTipText(object sender, ToolTipEventArgs e)
        {
            if (e.HitTestResult.ChartElementType == ChartElementType.DataPoint)
            {
                int i = e.HitTestResult.PointIndex;
                DataPoint dp = e.HitTestResult.Series.Points[i];
                DateTime time = DateTime.FromOADate(dp.XValue);
                // string str = time.ToString("yyyy-MM-dd HH:mm:ss")+"\n";
                // e.Text = string.Format("{0:F3}", dp.YValues[0]);
                // Console.WriteLine(dp.Name);
                string str = "";
                for (int j = 0; j < 15; j++)
                {
                    if (chart1.Series[j].Enabled && chart1.Series[j].Points.Count > 0)
                        str += chart1.Series[j].Name + ": " + chart1.Series[j].Points[i].YValues[0].ToString() + "\n";
                }

                e.Text = str;
            }
        }

        private bool isSelectAll = false;
        private bool isSingleSelect = false;

        private void allselect_chb_CheckedChanged(object sender, EventArgs e)
        {
            if (isSingleSelect == true) return;
            selectall(allselect_chb.Checked);
            isSelectAll = allselect_chb.Checked;
            isSingleSelect = false;
        }

        private void selectall(bool check)
        {
            data1_chb.Checked = check;
            data2_chb.Checked = check;
            data3_chb.Checked = check;
            data4_chb.Checked = check;
            data5_chb.Checked = check;
            data6_chb.Checked = check;
            data7_chb.Checked = check;
            data8_chb.Checked = check;
            data9_chb.Checked = check;
            data10_chb.Checked = check;
            data11_chb.Checked = check;
            data12_chb.Checked = check;
            data13_chb.Checked = check;
            data14_chb.Checked = check;
            data15_chb.Checked = check;
        }

        private void data_chb_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            if (cb.Checked == false)
            {
                isSingleSelect = true;
                allselect_chb.Checked = false;
            }

            int index;
            Console.WriteLine(cb.Name.Length + cb.Name);
            if (cb.Name.Length == 9)
                index = Convert.ToInt32(cb.Name.Substring(4, 1));
            else
                index = Convert.ToInt32(cb.Name.Substring(4, 2));
            chart1.Series[index - 1].Enabled = cb.Checked;
            //判断是否全选
            if (data1_chb.Checked && data2_chb.Checked && data3_chb.Checked && data4_chb.Checked && data5_chb.Checked &&
                data6_chb.Checked && data7_chb.Checked && data8_chb.Checked && data9_chb.Checked &&
                data10_chb.Checked &&
                data11_chb.Checked && data12_chb.Checked && data13_chb.Checked && data14_chb.Checked &&
                data15_chb.Checked)
            {
                allselect_chb.Checked = true;
            }
        }

        private void allselect_chb_MouseDown(object sender, MouseEventArgs e)
        {
            isSingleSelect = false;
        }

        private void showchartdata_chb_CheckedChanged(object sender, EventArgs e)
        {
            // throw new System.NotImplementedException();
            this.isShowOriginData = showchartdata_chb.Checked;
        }

        private void ysize_nud_ValueChanged(object sender, EventArgs e)
        {
            // throw new System.NotImplementedException();
            chart1.ChartAreas[0].AxisY.ScaleView.Size = (double)ysize_nud.Value;
            isAotoSize = false;
        }

        private void xsize_nud_ValueChanged(object sender, EventArgs e)
        {
            // throw new System.NotImplementedException();
            chart1.ChartAreas[0].AxisX.ScaleView.Size = (double)xsize_nud.Value;
            isAotoSize = false;
        }
    }
}